// ------------------------------------------------------------------------------------
// REVISION LOG ENTRY
//
//  File name  : class Tkit.DragWindow
//  Revision By: (C) Copyright 2014 Hiroyuki Tominaga, All Rights Reserved.
//
//  Revised on : 2014-06-20 01:36:48
//  Summary    : version 1.0.2
//               code google: https://js-tkit-project.googlecode.com/svn/trunk/tkit-dragwindow.js
//               js.doit    : http://jsrun.it/motrohi/tkit-dragwindow/js
//
//  http://jsfiddle.net/motrohi/U698c/
//  http://jsdo.it/motrohi/tkit-dragwindow
//
// ------------------------------------------------------------------------------------


(function(name_space) {

    var _DEBUG = false;
    var tkit, _gasp; {
        var W = (window || self);
        W.$ = W.$ || {};
        /* getActualScrollPosition */
        // from :https://developer.mozilla.org/ja/docs/Web/API/window.scrollY
        _gasp = W.getActualScrollPosition || $.gasp || function gasp() {
            var x = (window.pageXOffset !== undefined)?
                window.pageXOffset: (document.documentElement || document.body.parentNode || document.body).scrollLeft,
            y = (window.pageYOffset !== undefined)?
                window.pageYOffset : (document.documentElement || document.body.parentNode || document.body).scrollTop;
            return { scrollX: x, scrollY: y };
        };
        /* */
        tkit = W[name_space];
        (!tkit) && ( tkit = W[name_space] = {} );
        if (!W.$.noop) {
            W.$.noop = function(){};
        }
    }

    var _al = "addEventListener", _rl = "removeEventListener";

    tkit.DragWindow = function DragWindow(element, capturePhaze, callback)
    {
        if ( "extendBase" in tkit && typeof tkit.extendBase === "function")
            tkit.extendBase(this, tkit.DragWindow, arguments);

        var _x = 0, _y = 0, _e, _id;

        this.release = function() {
            this.reset();
            _removeListener();
            // capturePhaze parameter を "true" としていたために削除が失敗していた(chrome
            // capturePhaze parameter を使っていなかったということ.
            _e && _e[_rl]('mousedown', _mdown, capturePhaze);
            Manager.remove(_e);
            _e = null, _id = "";
            if (tkit.DEBUG) console.log(Manager);
        };
        this.reset = function() {
            _x = 0, _y = 0;
        };
        this.setTarget = function(element) {
            this.release();
            _e = (element && typeof element !== "string")? element: null;
            try {
                _id = (element && typeof element === "string")? element: element.id;
            } catch (e) {
                console.log(e);
                _id = "";
            }
            _addListener();
            Manager.add(_e);
        };

        function logEvent(e) {
            if (!callback) return;
            callback(e);
        }
        /* If define as a prototype apparently a reference function seems to fail */
        /**
         * !!need implemented as closure function
         */
        function _addListener() {
            var target = _e;
            // lazy initiaize?.
            if (target === null) {
                _e = target = document.getElementById(_id);
            }
            target[_al]('mousedown', _mdown, capturePhaze);
        };
        function _removeListener() {
            if (_e) {
                _e[_rl]('mousemove', _dragmove, capturePhaze);
                _e[_rl]('mouseup', _mup, capturePhaze);
            }
        };


        function _mdown(e) {
            if (!e) e = window.event;
            logEvent(e);
            if (e.target.id === _id) {
                if (e.offsetX === undefined) { // firefox 対応.
                    _x = e.layerX, _y = e.layerY;
                } else {
                    _x = e.offsetX, _y = e.offsetY;
                }
                _e[_al]('mousemove', _dragmove, capturePhaze);
                _e[_al]('mouseup', _mup, capturePhaze);
                Manager.mostTop(e.target);
                e.preventDefault();
            }
        };
        function _dragmove(e) {
            if (!e) e = window.event;
            logEvent(e);
            var ss = _e.style;
            var wposition = _gasp();
            ss.position = 'absolute';
            ss.top = e.clientY - _y + wposition.scrollY + 'px';
            ss.left = e.clientX - _x + wposition.scrollX + 'px';
            //console.log(e.type);
            e.preventDefault();
        };
        function _mup(e) {
            if (!e) e = window.event;
            logEvent(e);
            _removeListener(), e.preventDefault();
        };

        capturePhaze === undefined && (capturePhaze = false);
        this.setTarget(element);
    };

    /* singleton */
    var Manager = {
        lock: false,
        elements: [],
        add: function(element) {
            if (element && !this.lock)
                this.elements.push(element);
        },
        remove: function(element) {
            if (element && !this.lock) {
                this.lock = true;
                var arry = this.elements;
                var found;
                for (var i in arry) {
                    if (arry[i] === element) {
                        arry.splice(i, 1);
                        break;
                    }
                }
                this.lock = false;
            }
        },
        mostTop: function(element) {
            if (element && !this.lock) {
                this.lock = true;
                var arry = this.elements, max = 0, zIndex = 0;
                for (var i in arry) {
                    var e = arry[i];
                    if (e !== element) {
                        zIndex = parseInt(e.style.zIndex);
                        isNaN(zIndex) && (zIndex = 0), zIndex > max && (max = zIndex);
                    }
                }
                var zIndex2 = parseInt(element.style.zIndex);
                isNaN(zIndex2) && (zIndex2 = 0), zIndex2 <= max && (element.style.zIndex = max + 1);
                this.lock = false;
            }
        }
    };

})("Tkit"); // (function()
// ---------------------------------------------------------------------
